package com.baomidou.kisso.service.ym.impl;

import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.dto.Result;
import com.baomidou.kisso.dto.ResultCode;
import com.baomidou.kisso.dto.ResultGenerator;
import com.baomidou.kisso.security.token.SSOToken;
import com.baomidou.kisso.service.ym.AccountService;
import com.baomidou.kisso.service.ym.LoginService;
import com.baomidou.kisso.service.ym.TokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class LoginServiceImpl implements LoginService {
    public static final Logger logger = LoggerFactory.getLogger(LoginServiceImpl.class);
    @Autowired
    private TokenService tokenService;
    @Autowired
    private AccountService accountService;

    @Override
    public Result login(String account, String password, HttpServletRequest request, HttpServletResponse response) {
        //1.获取token
        String token = tokenService.getToken();
        //2.校验用户是否存在
        if(token!=null && token!=""){
            //校验用户是否存在
            Result accountResult = accountService.verification(token,account,password);
            if(accountResult.getCode()!= ResultCode.SUCCESS.code){
                return accountResult;
            }
            //3保存cookie
            SSOToken ssoToken = new SSOToken();
            ssoToken.setData(accountResult.getData());
            ssoToken.setIp(request);
            SSOHelper.setCookie(request, response, SSOToken.create().setData(accountResult.getData()).setIp(request).setId(1000).setIssuer("sso"), false);
            logger.info("suc","create cookie suc!");
            return ResultGenerator.genSuccessResult("验证成功");
        }else{
            logger.info("登录错误");
            return ResultGenerator.genFailResult("鉴权错误!");
        }
    }

    @Override
    public void loginOut(HttpServletRequest request, HttpServletResponse response) {
        logger.info("退出登录清楚 cookie 信息");
        SSOHelper.clearLogin(request, response);
    }


}
